﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MODEL;
using Dapper;
using MySql.Data.MySqlClient;

namespace DAL
{
    public class RoleDAL
    {     
        public static Task<IEnumerable<Role>> QueryRole(int? userId = null)
        {
            string sql = @"SELECT DISTINCT 
                            R.id
                            ,R.role_name AS RoleName
                            ,R.role_sign AS RoleSign
                            ,R.description
                            FROM msap_db.role R
                            LEFT JOIN msap_db.user_role U
                            ON U.role_id = R.id 
                            WHERE (@UserId IS NULL OR U.user_id = @UserId)";

            using (MySqlConnection conn = new MySqlConnection(AppSetting.Instance.MySqlConnectionStr))
            {
                return conn.QueryAsync<Role>(sql, new { UserId = userId });
            }
        }

        public static Task<int> UpdateUserRole(int userId, int roleId)
        {
            string sql = @"
                        UPDATE msap_db.user_role
                        SET role_id = @RoleId
                        WHERE user_id = @UserId
                        LIMIT 1";
            using (MySqlConnection conn = new MySqlConnection(AppSetting.Instance.MySqlConnectionStr))
            {
                return conn.ExecuteAsync(sql, new
                {
                    RoleId = roleId,
                    UserId = userId
                });
            }
        }
    }
}
